package com.fujimana.android.manacode;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.View;

public class FileListDialog extends Activity implements View.OnClickListener,
		DialogInterface.OnClickListener {

	private Context _parent = null;
	private File[] _dialog_file_list;
	private int _select_count = -1;
	private FileListDialogListener _listener = null;
	private boolean _is_directory_select = false;

	public void setDirectorySelect(boolean is) {
		_is_directory_select = is;
	}

	public boolean isDirectorySelect() {
		return _is_directory_select;
	}

	public String getSelectedFileName() {
		String ret = "";
		if (_select_count < 0) {

		} else {
			ret = _dialog_file_list[_select_count].getName();
		}
		return ret;
	}

	public FileListDialog(Context context) {
		_parent = context;
	}

	@Override
	public void onClick(View v) {
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		_select_count = which;
		if ((_dialog_file_list == null) || (_listener == null)) {
		} else {
			File file = _dialog_file_list[which];
			if (file.isDirectory() && !isDirectorySelect()) {
				show(file.getAbsolutePath(), file.getPath());
			} else {
				_listener.onClickFileList(file);
			}
		}
	}

	public void show(String path, String title) {

		try {
			_dialog_file_list = new File(path).listFiles();
			if (_dialog_file_list == null) {

				if (_listener != null) {
					_listener.onClickFileList(null);
				}
			} else {
				String[] list = new String[_dialog_file_list.length];
				int count = 0;
				String name = "";

				for (File file : _dialog_file_list) {
					if (file.isDirectory()) {
						name = file.getName() + "/";
					} else {
						name = file.getName();
					}
					list[count] = name;
					count++;
				}

				new AlertDialog.Builder(_parent).setTitle(title)
						.setItems(list, this).show();
			}
		} catch (SecurityException se) {

		} catch (Exception e) {

		}

	}

	public void setOnFileListDialogListener(FileListDialogListener listener) {
		_listener = listener;
	}

	public interface FileListDialogListener {
		public void onClickFileList(File file);
	}

}
